# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Project Name: luffcity study project
File Name: download_video.py
Author: kij
Create Date: 2021/2/12
-------------------------------------------------
"""
import os
import requests
from module_two.day15.homework import config


# 下载文件
def download(video_url,video_name):
	print(video_url)
	res = requests.get(
		url=video_url,
		headers = {
			"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36"
		}
	)

	# 视频总大小（字节）
	# 这里不太对，下载下来的字节不对
	file_size = int(res.headers['Content-Length'])
	download_size = 0
	with open(os.path.join(config.BASE_DIR, "files", (video_name + ".mp4")), mode='wb') as file_object:
		for chunk in res.iter_content(128):
			download_size += len(chunk)
			file_object.write(chunk)
			file_object.flush()
			percent = "\r{}%".format(int(round(download_size / file_size, 2) * 100))
			print(percent, end="")
		file_object.close()
	print("\n下载完成")
	res.close()

# 搜索
def search_id(video_id):
	name = ''
	video_url = ""
	with open(config.VIDEO_PATH, mode='rt', encoding='utf-8') as file_video:
		for line in file_video:
			video_message = line.split(",")
			if int(video_id) == int(video_message[0]):
				name = video_message[1]
				video_url = video_message[-1]
				break
	if not name:
		print("查询不到视频id为:{}的视频新闻".format(video_id))
	else:
		print("查询到新闻:{}\n正在下载".format(name))
		download(video_name=name,video_url=video_url)


def download_video():
	while True:
		num = input("输入id进行下载，【q或Q退出】:").strip()
		if num.upper() == "Q":
			break
		if not num.isdecimal():
			print("输入id错误请重新输入")
		else:
			search_id(num)


